package com.travel.Controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.travel.util.R;
import io.swagger.annotations.ApiOperation;
import org.bytedeco.opencv.presets.opencv_core;
import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("UploadFile")
public class UplaodFileColtroller {

    @Value("${travel.dPath}")
    private String uploadPath;
    //获取管理员名称
    public String getUsername() {
        String username;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }


    /**
     * uplaod媒体
     *
     * @param media 媒体
     * @return {@link R}
     * @throws IOException ioexception
     */
    @ApiOperation("富文本编辑器的图片、视频上传接口")
    @RequestMapping("upload-media")
    public R uplaod_media(@RequestParam("file") MultipartFile media) throws IOException {

        String mediaUrl = saveFile(uploadPath+"/"+getUsername(),media);
        if(mediaUrl.equals("0"))
            return R.no(1,"文件保存错误");
        mediaUrl = mediaUrl.replaceAll("\\\\","/");
        Map<String,String> map = new HashMap<>();

        System.out.println(Objects.requireNonNull(media.getContentType()).indexOf("ideo/"));

        map.put("url",mediaUrl);
        if(media.getContentType().indexOf("ideo/")>0){

        }else{
            map.put("alt",mediaUrl.substring(mediaUrl.lastIndexOf("/")+1));
            map.put("href", map.get("url"));
        }

        return R.ok(0,map);
    }


    /**
     * 项目媒体
     *
     * @param file    文件
     * @param session 会话
     * @return {@link Map}<{@link String},{@link String}>
     * @throws IOException ioexception
     */
    @ApiOperation("项目介绍中的图片上传")
    @PostMapping("ticket-media")
    public Map<String,String> ticket_media(MultipartFile file, HttpSession session) throws IOException {

        Map<String,String> imgsPath= new HashMap<>();

        String mediaUrl = saveFile(uploadPath+"/"+getUsername(),file);
        mediaUrl = mediaUrl.replaceAll("\\\\","/");

        String mediaName = file.getOriginalFilename();

        /*如果是存放的第一张图片，就现在session中创建相应的键内容
        * 如果不是那么就在已有的键值内容上做修改*/
        if(session.getAttribute("imgNum") == null){
            imgsPath.put(mediaName,mediaUrl);
            session.setAttribute("imgNum",1);
            session.setAttribute("imgsPath",imgsPath);
        }else{
            int SimgNum = (Integer)session.getAttribute("imgNum");
            Map<String,String> SimgsPath = (Map<String, String>) session.getAttribute("imgsPath");
            if(SimgNum <= 6){
                SimgsPath.put(mediaName,mediaUrl);
                SimgNum++;
                session.setAttribute("imgNum",SimgNum);
                session.setAttribute("imgsPath",SimgsPath);
            }
        }

        /*返回保存成功的文件的文件名（并不是保存到服务器的文件名，是原始名称）*/
        Map<String,String> map = new HashMap<>();
        map.put("success",mediaName);

        return map;

    }


    /**
     * 保存文件
     *
     * @param dirPaht dir paht
     * @param media   媒体
     * @return {@link String}
     * @throws IOException ioexception
     */
    private String saveFile(String dirPaht,MultipartFile media) throws IOException {
        /*获取当前的时间，文件名中不可以出现冒号（“：”）*/
        String date = DateTime.now().toString("yyyy-MM-dd hh_mm_ss");


        File dir = new File(uploadPath+"/"+getUsername());
        if(!dir.exists())
            dir.mkdirs();
        /*创建本地文件时，在原文件名的前面加上保存文件的时间，以保证文件的唯一和不冲突*/
        File file = new File(dir.getPath()+"/"+date+"-"+media.getOriginalFilename());
        if (!file.exists())
            file.createNewFile();

        /*文件流输出错误时，返回0*/
        try(FileOutputStream fileOutputStream = new FileOutputStream(file);){
            fileOutputStream.write(media.getBytes());
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("媒体文件上传错误");
            return "0";
        }

        /*返回文件所在的静态文件路径*/
        return file.getPath();
    }




}
